package com.sduept.nwld.dataserver.controller.equipment.assessment;

import com.alibaba.excel.EasyExcel;
import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.document.entity.core.RecordImage;
import com.sduept.bigdata.document.enums.AttachmentType;
import com.sduept.bigdata.document.services.RecordImageService;
import com.sduept.bigdata.equipment.assessment.dto.InspectionStationWithWaitingDTO;
import com.sduept.bigdata.equipment.assessment.enums.InspectionType;
import com.sduept.bigdata.equipment.assessment.enums.ItemTypeEnum;
import com.sduept.bigdata.equipment.assessment.enums.SubStationTypeEnum;
import com.sduept.bigdata.equipment.assessment.exception.ParameterException;
import com.sduept.bigdata.equipment.assessment.model.hiddendanger.track.RectificationPlan;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionExpert;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionItem;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionPlan;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionQuestionEquipment;
import com.sduept.bigdata.equipment.assessment.model.inspection.InspectionStation;
import com.sduept.bigdata.equipment.assessment.service.InspectionExpertService;
import com.sduept.bigdata.equipment.assessment.service.InspectionItemService;
import com.sduept.bigdata.equipment.assessment.service.InspectionPlanService;
import com.sduept.bigdata.equipment.assessment.service.InspectionQuestionEquipmentService;
import com.sduept.bigdata.equipment.assessment.service.InspectionStationService;
import com.sduept.bigdata.equipment.assessment.service.RectificationPlanService;
import com.sduept.bigdata.equipment.assessment.service.impl.DeductionTaskService;
import com.sduept.bigdata.weather.map.MapDataCache;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.cim.ledger.excetpion.ManagementUnitException;
import com.sduept.cim.ledger.manager.SubstationLedgerManager;
import com.sduept.cim.ledger.model.ManagementUnitDict;
import com.sduept.cim.ledger.model.SubstationLedger;
import com.sduept.cim.ledger.services.ManagementUnitService;
import com.sduept.cim.model.core.Substation;
import com.sduept.nwld.dataserver.controller.equipment.assessment.excel.ExportInspectionItemDTO;
import com.sduept.nwld.dataserver.controller.equipment.assessment.excel.InspectionItemExcelDataListener;
import com.sduept.nwld.dataserver.manager.message.MosMessagePushManager;
import com.sduept.permission.entity.DepartmentEntityBean;
import com.sduept.permission.entity.PersonnelEntityBean;
import com.sduept.permission.entity.RoleEntityBean;
import com.sduept.permission.manager.DepartManager;
import com.sduept.permission.manager.PersonnelManager;
import com.sduept.utils.Base64;
import com.sduept.utils.PingYinUtil;
import com.sduept.utils.ZipUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.PrimeFaces;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.NodeExpandEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.TreeNode;
import org.primefaces.model.UploadedFile;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.stream.Collectors;

/**
 * 待办评价项展示页面控制器
 *
 * @author pengz
 */
@Slf4j
@Named
@ViewScoped
public class WaitingTaskController extends AbstractController {

    private static final long serialVersionUID = -8005825584973743926L;

    @Inject
    private InspectionStationService stationService;
    @Inject
    private InspectionItemService itemService;
    @Inject
    private InspectionPlanService planService;
    @Inject
    private InspectionExpertService expertService;
    @Inject
    private ManagementUnitService unitService;
    @Inject
    private SubstationLedgerManager stationLedgerM;
    @Inject
    private MapDataCache cc;
    @Inject
    private DeductionTaskService deductService;
    @Inject
    private RecordImageService imageService;
    @Inject
    private CommonDocumentProperties commonDocumentProperties;
    @Inject
    private InspectionQuestionEquipmentService qeService;
    @Inject
    private RectificationPlanService rectificationPlanService;
    @Inject
    private MosMessagePushManager mosMessM;
    @Inject
    private DepartManager dm;
    @Inject
    private PersonnelManager pm;
    private TreeNode root = new DefaultTreeNode();
    /**
     * 当前用户可见的所有的待办任务，即页面中的下拉列表所展示的内容
     */
    private List<InspectionPlan> allWaitingTasks = new ArrayList<InspectionPlan>();
    /**
     * 专家
     */
    private InspectionExpert expert;
    /**
     * 角色是否为管理员，可以看到所有的待办任务
     */
    private boolean isAdmin = false;
    /**
     * 是否为专家，可以看到该专家下的待办任务
     */
    private boolean isExpert = false;
    /**
     * 设备评估管理员角色，可以看到该部门下的所有的待办任务
     */
    private boolean isEvaluation = false;
    /**
     * 状态颜色
     */
    private String statusColor;
    /**
     * key为计划，value为检查站的DTO
     */
    private Map<InspectionPlan, List<InspectionStationWithWaitingDTO>> map = new HashMap<InspectionPlan, List<InspectionStationWithWaitingDTO>>();

    private InspectionStationWithWaitingDTO selectedWaitingModel = new InspectionStationWithWaitingDTO();
    //是否是当前专家登录
    private boolean currentExpertlogin;
    private Map<String, InspectionStationWithWaitingDTO> stationWaitingDtoMap = new HashMap<String, InspectionStationWithWaitingDTO>();
    private Map<String, ToDoAssessmentModel> todoMap = new HashMap<String, WaitingTaskController.ToDoAssessmentModel>();
    /**
     * 所有的变电站map集合，初始化时获得，key:id
     */
    private Map<String, Substation> stationMap;
    private Map<String, Boolean> stationIdToHasItems = new HashMap<String, Boolean>();
    private Map<String, InspectionStation> stationIdToStationMap = new HashMap<String, InspectionStation>();
    private Map<String, Substation> stationNameToSubstationMap = new HashMap<String, Substation>();
    /**
     * <专家名称,专家对象>
     */
    private Map<String, InspectionExpert> expertMap = new HashMap<String, InspectionExpert>();
    /**
     * 导入检查站信息选中的记录
     */
    private ToDoAssessmentModel todoModel;
    /**
     * 导出检查站的评价详情
     */
    private StreamedContent exportFile;
    /**
     * true：删掉原有数据并导入
     * false：合并原有数据并导入
     */
    private boolean isDeleteBeforeImport = false;
    /**
     * true:当前变电站有已完成的评价项
     * false:当前变电站还未进行评价
     */
    private boolean hasFinishedItem = false;

    private RectificationPlan createTrackDemo = new RectificationPlan();
    /**
     * 选择的整改负责人
     */
    private PersonnelEntityBean selectedPerson = null;

    @PostConstruct
    public void init() {
        expertMap = getAllExpert();
        currentUserIdentity();
        getWaitingTasksByCurrentUser();
        initPlanTreeTable(allWaitingTasks);
        stationMap = cc.getStationid_map();
    }

    /**
     * 判断当前用户的身份
     * 如果是管理员，则isAdmin=true
     * 如果是专家，则isExpert=true
     * 管理员的优先级高于专家
     */
    private void currentUserIdentity() {
        isAdmin = false;
        PersonnelEntityBean user = getCurrentUser();
        // 判断是否为管理员
        Set<RoleEntityBean> roles = user.getRoles();
        for (RoleEntityBean role : roles) {
            if ("system".equals(role.getType())) {
//			if("管理员".equals(role.getName())) {
                isAdmin = true;
                break;
            } else if ("设备评估管理".equals(role.getName())) {
                isEvaluation = true;
            }
        }
        // 判断是否为专家
        if (!isAdmin && !isEvaluation) {
            String userCode = user.getCode();
            expert = expertService.findByCode(userCode);
            if (null != expert) {
                isExpert = true;
            }
        }
    }

    /**
     * 获取当前用户可看的所有的待办任务
     * 如果是管理员，可以查看所有
     * <p>
     * 如果是专家，可以查看自己的待办任务，以及待办任务下分配给自己的变电站
     * 如果是普通用户，则无法查看
     */
    private void getWaitingTasksByCurrentUser() {
        // 当前用户是管理员
        if (isAdmin) {
            getWaitingTasksByAdmin();
        } else if (isEvaluation) {
            // 是设备评估管理人员
            getWaitingTasksByEvaluationManager();
        } else if (isExpert) {
            // 专家
            getWaitingTasksByExpert();
        } else {
            // 首先判断当前用户是否为计划的负责人
            allWaitingTasks = planService.findInspectionPlanByCondition(null, getCurrentUser().getName(), null, null, null);
            genPlanAndStationMap(allWaitingTasks);
            try {
                // 被检单位迎检人员登录
                Map<InspectionPlan, List<InspectionStationWithWaitingDTO>> stationPersonnelMap = stationService.findWaitingTaskByStationPersonnel(getCurrentUser().getName());
                if (map.isEmpty()) {
                    map = stationPersonnelMap;
                    allWaitingTasks.addAll(map.keySet());
                } else {
                    for (InspectionPlan inspectionPlan : stationPersonnelMap.keySet()) {
                        List<InspectionStationWithWaitingDTO> stationWaitingDtos = stationPersonnelMap.get(inspectionPlan);
                        InspectionPlan tPlan = null;
                        for (InspectionStationWithWaitingDTO stationWaitingDto : stationWaitingDtos) {
                            boolean save = true;
                            label1:
                            for (InspectionPlan plan : map.keySet()) {
                                List<InspectionStationWithWaitingDTO> swds = map.get(plan);
                                if (plan.getId().equals(inspectionPlan.getId())) {
                                    tPlan = plan;
                                }
                                for (InspectionStationWithWaitingDTO swd : swds) {
                                    if (stationWaitingDto.getId().equals(swd.getId())) {
                                        save = false;
                                        break label1;
                                    }
                                }
                            }
                            if (save) {
                                if (tPlan != null) {
                                    map.get(tPlan).add(stationWaitingDto);
                                } else {
                                    if (!map.containsKey(inspectionPlan)) {
                                        map.put(inspectionPlan, new ArrayList<InspectionStationWithWaitingDTO>());
                                    }
                                    map.get(inspectionPlan).add(stationWaitingDto);
                                }
                            }
                        }
                    }
                    for (InspectionPlan inspectionPlan : map.keySet()) {
                        if (!allWaitingTasks.contains(inspectionPlan)) {
                            allWaitingTasks.add(inspectionPlan);
                        }
                    }
//					allWaitingTasks.addAll(map.keySet());
                }
            } catch (ParameterException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 当前用户是管理员，可见的待办任务范围：
     */
    private void getWaitingTasksByAdmin() {
        allWaitingTasks = planService.findAllUnFinishPlanWithOutStation();
        genPlanAndStationMap(allWaitingTasks);
    }

    /**
     * 当前用户是专家，可见的待办任务范围
     */
    private void getWaitingTasksByExpert() {
        try {
            map = stationService.findWaitingTaskByExpertCodeAndName(expert.getCode(), expert.getName());
            allWaitingTasks.addAll(map.keySet());
        } catch (ParameterException e) {
            e.printStackTrace();
            addErrorMessage("获取专家未完成的变电站失败");
        }
    }

    /**
     * 当前用户是设备评估管理员，可见的待办任务范围
     */
    private void getWaitingTasksByEvaluationManager() {
        PersonnelEntityBean user = getCurrentUser();
        DepartmentEntityBean pdept = dm.findPersonDepart(user.getCode());
        DepartmentEntityBean dept = recursionGetDept(pdept);
        // 根据dept获取该部门下的所有的检查站
        if (null == dept) {
            return;
        }
        List<InspectionStation> allStations = stationService.findByAcceptDept(dept.getName());
        Map<InspectionPlan, List<InspectionStation>> planAndStationMap = allStations.stream().collect(Collectors.groupingBy(InspectionStation::getInspectPlan));
        allWaitingTasks = new ArrayList<InspectionPlan>();
        // 下拉列表所显示的所有计划
        allWaitingTasks.addAll(planAndStationMap.keySet());
        for (InspectionPlan plan : planAndStationMap.keySet()) {
            List<InspectionStationWithWaitingDTO> dtos = new ArrayList<InspectionStationWithWaitingDTO>();
            List<InspectionStation> stations = planAndStationMap.get(plan);
            for (InspectionStation station : stations) {
                InspectionStationWithWaitingDTO dto = InspectionStationWithWaitingDTO.convertFormInspectionStation(station, plan);
                dtos.add(dto);
            }
            map.put(plan, dtos);
        }
    }

    /**
     * 如果是运维单位或者检修范围，返回本身；否则，递归向上查找父，直到其父为运维单位或者检修范围
     *
     * @param dept
     * @return
     */
    private DepartmentEntityBean recursionGetDept(DepartmentEntityBean dept) {
        if (null == dept) {
            return null;
        }
        // TODO 当前登录用户的部门类型为空时，要如何处理？
        if (StringUtils.isBlank(dept.getType())) {
            return dept;
        }
        if ("MAINTENANCE_SCOPE".equals(dept.getType()) || "MAINTENANCE_MANAGEMENT".equals(dept.getType())) {
            return dept;
        } else {
            if (null != dept.getParent()) {
                return recursionGetDept(dept.getParent());
            } else {
                return null;
            }
        }
    }

    private void genPlanAndStationMap(List<InspectionPlan> plans) {
        for (InspectionPlan plan : plans) {
            try {
                Set<InspectionStation> stationSet = stationService.findByInspectionPlan(plan.getId());
                List<InspectionStationWithWaitingDTO> dtos = new ArrayList<InspectionStationWithWaitingDTO>();
                for (InspectionStation inspectionStation : stationSet) {
                    InspectionStationWithWaitingDTO dto = InspectionStationWithWaitingDTO.convertFormInspectionStation(inspectionStation, plan);
                    stationIdToStationMap.put(inspectionStation.getId(), inspectionStation);
                    dtos.add(dto);
                }
                map.put(plan, dtos);
            } catch (ParameterException e) {
                e.printStackTrace();
                addErrorMessage("获取计划的检查站失败");
            }
        }
    }

    /**
     * 构造树，第一级：InspectionPlan 第二级：InspectionStation
     */
    private void initPlanTreeTable(List<InspectionPlan> plans) {
        root = new DefaultTreeNode();
        for (InspectionPlan plan : plans) {
            ToDoAssessmentModel planModel = genToDoAssessmentModelByPlan(plan);
            TreeNode planTreeNode = new DefaultTreeNode("InspectionPlan", planModel, root);
            List<InspectionStationWithWaitingDTO> dtos = map.get(plan);
            if (dtos.size() > 0) {
                InspectionStationWithWaitingDTO dto = dtos.get(0);
                ToDoAssessmentModel stationModel = genToDoAssessmentModelByStation(dto);
                new DefaultTreeNode("InspectionStation", stationModel, planTreeNode);
            }
        }
    }

    /**
     * 点击任务节点事件监听
     * @param event
     */
    public void onNodeExpand(NodeExpandEvent event) {
        TreeNode planNode = event.getTreeNode();
        planNode.getChildren().clear();
        ToDoAssessmentModel planModel = (ToDoAssessmentModel) planNode.getData();
        String planId = planModel.getPsId();
        InspectionPlan plan = planService.findById(planId);
        InspectionType inspectionType = plan.getInspectionType();
        List<InspectionStationWithWaitingDTO> dtos = new ArrayList<>();
        //互查
        if (InspectionType.INSPECTIONOTHER == inspectionType) {
            dtos = map.get(plan);
        }
        //自查
        else if (InspectionType.INSPECTIONSELF == inspectionType) {
            PersonnelEntityBean currentUser = getCurrentUser();
            String userCode = currentUser.getCode();
            Map<InspectionPlan, List<InspectionStation>> selfCheckInspectionStations = planService.findSelfCheckInspectionStations(userCode);
            List<InspectionStation> inspectionStations = selfCheckInspectionStations.get(plan);
            for (InspectionStation inspectionStation : inspectionStations) {
                InspectionStationWithWaitingDTO dto = InspectionStationWithWaitingDTO.convertFormInspectionStation(inspectionStation, plan);
                dtos.add(dto);
            }
        }
        //生成InspectionStation节点
        for (InspectionStationWithWaitingDTO dto : dtos) {
            ToDoAssessmentModel stationModel = genToDoAssessmentModelByStation(dto);
            new DefaultTreeNode("InspectionStation", stationModel, planNode);
        }
        planNode.setExpanded(true);
    }

    /**
     * 计划查询下拉列表
     *
     * @param query
     * @return
     */
    public List<InspectionPlan> complateInspectionPlan(String query) {
        List<InspectionPlan> result = new ArrayList<InspectionPlan>();
        for (InspectionPlan plan : allWaitingTasks) {
            String nameHead = PingYinUtil.getPingYinHeader(plan.getName());
            if (nameHead.toLowerCase().contains(query)) {
                result.add(plan);
            }
        }
        return result;
    }

    /**
     * 查看的计划变化时，重新渲染页面显示的数据
     *
     * @param event
     */
    public void changeSelectPlan(SelectEvent event) {
        String planId = (String) event.getObject();
        InspectionPlan plan = planService.findById(planId);
        List<InspectionPlan> plans = new ArrayList<InspectionPlan>();
        plans.add(plan);
        initPlanTreeTable(plans);
    }

    /**
     * 根据计划生成ToDoAssessmentModel
     *
     * @param plan
     * @return
     */
    private ToDoAssessmentModel genToDoAssessmentModelByPlan(InspectionPlan plan) {
        return new ToDoAssessmentModel(plan.getId(), plan.getName(), plan.getResponsible(), plan.getCreator(), plan.getStartTime(), plan.getEndTime(), plan.getActualStartTime(), plan.getActualEndTime(), plan.getStatus(), "InspectionPlan", "", "");
    }

    /**
     * 根据检查站生成ToDoAssessmentModel
     *
     * @param station
     * @return
     */
    private ToDoAssessmentModel genToDoAssessmentModelByStation(InspectionStationWithWaitingDTO dto) {
//		Set<InspectionExpert> experts = station.getExperts();
//		String expertStr = "";
//		if(experts.size()>0) {
//			for (InspectionExpert inspectionExpert : experts) {
//				expertStr+=inspectionExpert.getName();
//				expertStr+="  ";
//			}
//		}
        String name = "";
        if ("InspectionOther".equals(dto.getInspectionType())) {
            name = dto.getAcceptunit();
            if (StringUtils.isNotBlank(dto.getStationName())) {
                name += "【" + dto.getStationName() + "】";
            }
        } else {
            name = dto.getStationName();
        }
        ToDoAssessmentModel todo = new ToDoAssessmentModel(dto.getId(), name, "", "",
                dto.getStartTime(), dto.getEndTime(), dto.getActualStartTime(),
                dto.getActualEndTime(), dto.getStatus(), "InspectionStation", dto.getStationName(), dto.getInspectionExpert());
        todo.setInspectionType(dto.getInspectionType());
        stationWaitingDtoMap.put(dto.getId(), dto);
        todoMap.put(todo.getPsId(), todo);
        return todo;
    }

    /**
     * 根据int类型的状态对应指定汉字
     *
     * @param type
     * @param status
     * @return
     */
    public String getStatusStr(String type, int status) {
        String result = "";
        if ("InspectionPlan".equals(type)) {
            switch (status) {
                case 1:
                    result = "未开始";
                    statusColor = "red";
                    break;
                case 2:
                    result = "进行中";
                    statusColor = "blue";
                    break;
                case 3:
                    result = "已完成";
                    statusColor = "green";
                    break;
                default:
                    break;
            }
        } else {
            switch (status) {
                case 0:
                    result = "未开始";
                    statusColor = "red";
                    break;
                case 1:
                    result = "进行中";
                    statusColor = "blue";
                    break;
                case 2:
                    result = "已完成";
                    statusColor = "green";
                    break;
                default:
                    break;
            }
        }
        return result;

    }

    /**
     * 弹出故障详情对话框
     *
     * @param fault
     */
    public void openInspectionStationDetail2(ToDoAssessmentModel dto) {
        boolean isEditable = false;
        String eCode = dto.getExpert();
        if (isAdmin) {
            isEditable = true;
        } else if (expert != null) {
            if (null != eCode && eCode.contains(expert.getName())) {
//				if(expert.getCode().equals(eCode)) {
                isEditable = true;
            }
        } else {
            boolean flag = isPlanResponsible(dto, getCurrentUser().getName());
            if (flag) {
                // 是计划负责人
                isEditable = true;
            }
        }

        String path = "/ui/equipmentAssessment/assessmentplan/dialog/inspectionStation_detail_datatable.xhtml?id=" + dto.getPsId() + "&isEditable=" + isEditable;
        PrimeFaces.current().executeScript("openInspectionStationDetail('" + path + "')");
    }

    /**
     * 评价弹窗保存/提交后操作逻辑
     *
     * @author pengz
     */
    public void onDetailDialogReturn() {
        String mark = getParameter("mark");
        if ("save".equals(mark)) {
            addSuccessMessage("保存成功！");
            PrimeFaces.current().ajax().update(Arrays.asList("headForm:msgs"));
        } else if (mark.startsWith("submit-")) {
            String instationId = mark.split("-")[1];
            /**
             * 当前评价站
             */
//			InspectionStation currentStation = stationService.findById(instationId);
            if (todoMap.containsKey(instationId)) {
                ToDoAssessmentModel todo = todoMap.get(instationId);
                todo.setStatus(2);
            }
//			currentStation.setStatus(2);
//			stationService.update(currentStation);
//			InspectionPlan plan = currentStation.getInspectPlan();
//			List<InspectionPlan> plans = new ArrayList<InspectionPlan>();
//			plans.add(plan);
//			initPlanTreeTable(plans);
            addSuccessMessage("提交成功！");
            PrimeFaces.current().ajax().update(Arrays.asList("headForm:msgs", "form"));
        }
    }

    /**
     * 打开互查信息按钮是否渲染
     *
     * @param todo
     * @return
     */
    public boolean addStationInfoDialogRendered(ToDoAssessmentModel todo) {
        boolean rendered = false;
        if ("InspectionStation".equals(todo.getType())) {
            if ("InspectionOther".equals(todo.getInspectionType())) {//互查
                rendered = true;
            }
        }
        return rendered;
    }

    /**
     * 评价按钮是否渲染
     *
     * @param todo
     * @return
     */
    public boolean inspectBtnRendered(ToDoAssessmentModel todo) {
        if ("InspectionStation".equals(todo.getType())) {
            if ("InspectionOther".equals(todo.getInspectionType())) {//互查
                if (!stationIdToHasItems.containsKey(todo.getPsId())) {
                    List<InspectionItem> items = null;
                    try {
                        items = stationService.findInspectionItemByStationId(todo.getPsId());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (items == null || items.isEmpty()) {
                        stationIdToHasItems.put(todo.getPsId(), false);
                    } else {
                        stationIdToHasItems.put(todo.getPsId(), true);
                    }
                }
                return stationIdToHasItems.get(todo.getPsId());
            } else {
                return true;
            }
        }
        return false;
    }

    public void preOpenAddStationInfoDialog(ToDoAssessmentModel todo) {
        InspectionStationWithWaitingDTO model = stationWaitingDtoMap.get(todo.getPsId());
        selectedWaitingModel = model;
        InspectionStation instation = null;
        if (stationIdToStationMap.containsKey(selectedWaitingModel.getId())) {
            instation = stationIdToStationMap.get(selectedWaitingModel.getId());
        }
        if (instation != null) {
            model.setStationName(instation.getStationName());
        }
        if (isAdmin) {
            currentExpertlogin = true;
            isExpert = true;
            return;
        }
        boolean flag = isPlanResponsible(todo, getCurrentUser().getName());
        if (flag) {
            // 是计划负责人
            currentExpertlogin = true;
            isExpert = true;
        } else {
            String eCode = todo.getExpert();
            if (expert != null) {
                if (null != eCode && eCode.contains(expert.getName())) {
                    currentExpertlogin = true;
                }
            }
        }


    }

    /**
     * 判断用户是否为计划的负责人
     *
     * @param todo
     * @return
     */
    private boolean isPlanResponsible(ToDoAssessmentModel todo, String userName) {
        boolean flag = false;
        if ("InspectionPlan".equals(todo.getType())) {
            if (todo.getResponsible().equals(userName)) {
                flag = true;
            }
        } else if ("InspectionStation".equals(todo.getType())) {
            InspectionStation inspectionStation = deductService.getInspectionStationById(todo.getPsId());
            InspectionPlan plan = inspectionStation.getInspectPlan();
            String responsible = plan.getResponsible();
            if (userName.equals(responsible)) {
                flag = true;
            }
        }
        return flag;
    }

    public List<String> completeSubstations(String query) {
        List<String> result = new ArrayList<String>();
        List<Substation> substations = new ArrayList<Substation>();
        if (StringUtils.isNotBlank(selectedWaitingModel.getAcceptunit())) {
            try {
                ManagementUnitDict unit = unitService.getManagementUnitByName(selectedWaitingModel.getAcceptunit());
                if (unit != null) {
                    List<SubstationLedger> stationLedgers = stationLedgerM.querySubstationByVoltageAndMaintenanceUnit(null, unit);
                    for (SubstationLedger ledger : stationLedgers) {
                        Substation station = stationMap.get(ledger.getCimId());
                        if (station != null) {
                            substations.add(station);
                            stationNameToSubstationMap.put(station.getName(), station);
                        }
                    }
                }
            } catch (ManagementUnitException e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(query)) {
            for (Substation station : substations) {
                if (PingYinUtil.getPingYinHeader(station.getName()).startsWith(query)) {
                    result.add(station.getName());
                }
            }
        } else {
            for (Substation station : substations) {
                result.add(station.getName());
            }
        }
        return result;
    }
    /**
     * 变电站选中事件处理函数
     */
//	public void onSubstationSelect() {
//		Substation station = stationNameToSubstationMap.get(selectedWaitingModel.getStationName());
//		InspectionStation instation = null;
//		if(stationIdToStationMap.containsKey(selectedWaitingModel.getId())) {
//			instation = stationIdToStationMap.get(selectedWaitingModel.getId());
//		}else {
//			instation = stationService.findById(selectedWaitingModel.getId());
//			stationIdToStationMap.put(instation.getId(), instation);
//		}
//		instation.setStationId(station.getId());
//		instation.setStationName(station.getName());
//		instation.setVoltagelevel(station.getStandVoltagelevel());
//	}

    /**
     * 获得所有的变电站类型
     *
     * @return
     */
    public SubStationTypeEnum[] getStationTypes() {
        return SubStationTypeEnum.values();
    }

    /**
     * 生成评价表单
     */
    public void generateInspectionItems() {
        if (StringUtils.isBlank(selectedWaitingModel.getStationName())) {
            alertErrorMessage("请先选择变电站！");
            return;
        }
        if (StringUtils.isNotBlank(selectedWaitingModel.getStationType())) {
            SubStationTypeEnum type = null;
            for (SubStationTypeEnum stationType : SubStationTypeEnum.values()) {
                if (stationType.name().equals(selectedWaitingModel.getStationType())) {
                    type = stationType;
                    break;
                }
            }
            InspectionStation instation = null;
            if (stationIdToStationMap.containsKey(selectedWaitingModel.getId())) {
                instation = stationIdToStationMap.get(selectedWaitingModel.getId());
            } else {
                instation = stationService.findById(selectedWaitingModel.getId());
                stationIdToStationMap.put(instation.getId(), instation);
            }
            instation.setStationType(type);
            try {
                boolean success = itemService.generateStationInspectionItems(type, selectedWaitingModel.getId());
                stationIdToHasItems.put(selectedWaitingModel.getId(), success);
                stationService.update(instation);
                save();
                addSuccessMessage("检查表单导入成功！");
            } catch (ParameterException e) {
                e.printStackTrace();
            }
        }

    }

    public void clearInspectionItems() {
        List<InspectionItem> items = itemService.findBySubId(selectedWaitingModel.getId());
        for (InspectionItem item : items) {
            itemService.deleteById(item.getId());
        }
        stationIdToHasItems.replace(selectedWaitingModel.getId(), false);
        InspectionStation instation = null;
        if (stationIdToStationMap.containsKey(selectedWaitingModel.getId())) {
            instation = stationIdToStationMap.get(selectedWaitingModel.getId());
        } else {
            instation = stationService.findById(selectedWaitingModel.getId());
            stationIdToStationMap.put(instation.getId(), instation);
        }
        instation.setDeduct(0.0f);
        instation.setRealDeduct(0.0f);
        instation.setStatus(1);
        instation.setActualStartTime(null);
        instation.setActualEndTime(null);
        instation.setStationType(null);
        selectedWaitingModel.setStationType(null);
        stationService.update(instation);
        //从扣分服务缓存中清除
        deductService.clearInspectionStationCacheBySid(instation.getId());
        addSuccessMessage("重置完成！请重新生成检查表单");
    }

    public boolean hasInspectionItems() {
        if (isExpert) {
            if (StringUtils.isNotBlank(selectedWaitingModel.getId())) {
                if (stationIdToHasItems.containsKey(selectedWaitingModel.getId())) {
                    return stationIdToHasItems.get(selectedWaitingModel.getId());
                } else {
                    List<InspectionItem> items = null;
                    try {
                        items = stationService.findInspectionItemByStationId(selectedWaitingModel.getId());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (items == null || items.isEmpty()) {
                        stationIdToHasItems.put(selectedWaitingModel.getId(), false);
                    } else {
                        stationIdToHasItems.put(selectedWaitingModel.getId(), true);
                    }
                    return stationIdToHasItems.get(selectedWaitingModel.getId());
                }
            }
            return false;
        } else {
            return true;
        }

    }

    /**
     * 生成检查表单按钮是否可用
     *
     * @return
     */
    public boolean disabledGenerateItemBtn() {
        if (currentExpertlogin) {
            if (StringUtils.isNotBlank(selectedWaitingModel.getStationType())) {
                if (hasInspectionItems()) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        } else {
            return true;
        }

    }

    /**
     * 重置按钮是否可用
     *
     * @return
     */
    public boolean disabledClearBtn() {
        if (currentExpertlogin) {
            if (hasInspectionItems()) {
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }

    }

    /**
     * 保存
     */
    public void save() {
        if (StringUtils.isBlank(selectedWaitingModel.getStationName())) {
            alertErrorMessage("请选择变电站！");
            return;
        }
        if (selectedWaitingModel.getStartTime() == null || selectedWaitingModel.getEndTime() == null) {
            alertErrorMessage("请选择检查时间！");
            return;
        }
        if (StringUtils.isBlank(selectedWaitingModel.getStationType())) {
            alertErrorMessage("请选择抽检类型！");
            return;
        }
        if (!stationIdToHasItems.containsKey(selectedWaitingModel.getId())) {
            List<InspectionItem> items = null;
            try {
                items = stationService.findInspectionItemByStationId(selectedWaitingModel.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (items == null || items.isEmpty()) {
                stationIdToHasItems.put(selectedWaitingModel.getId(), false);
            } else {
                stationIdToHasItems.put(selectedWaitingModel.getId(), true);
            }
        }
        if (!stationIdToHasItems.get(selectedWaitingModel.getId())) {
            alertErrorMessage("请生成检查表单！");
            return;
        }
        InspectionStation instation = null;
        if (stationIdToStationMap.containsKey(selectedWaitingModel.getId())) {
            instation = stationIdToStationMap.get(selectedWaitingModel.getId());
        } else {
            instation = stationService.findById(selectedWaitingModel.getId());
            stationIdToStationMap.put(instation.getId(), instation);
        }
        if (instation.getStationName() == null || !instation.getStationName().equals(selectedWaitingModel.getStationName())) {
            Substation station = stationNameToSubstationMap.get(selectedWaitingModel.getStationName());
            instation.setStationId(station.getId());
            instation.setStationName(station.getName());
            instation.setVoltagelevel(station.getStandVoltagelevel());
            deductService.clearInspectionStationCacheBySid(instation.getId());
        }

        instation.setStartTime(selectedWaitingModel.getStartTime());
        instation.setEndTime(selectedWaitingModel.getEndTime());
//		instation.setStationName(selectedWaitingModel.getStationName());
        stationService.update(instation);
        ToDoAssessmentModel todo = todoMap.get(selectedWaitingModel.getId());
        todo.setStartTime(selectedWaitingModel.getStartTime());
        todo.setEndTime(selectedWaitingModel.getEndTime());
        todo.setActualStratTime(instation.getActualStartTime());
        todo.setActualEndTime(instation.getActualEndTime());
        todo.setStatus(instation.getStatus());
        String name = todo.getName();
        if (name.contains("【")) {
            name = name.substring(0, name.indexOf("【"));
        }
        if (StringUtils.isNotBlank(selectedWaitingModel.getStationName())) {
            name = name + "【" + selectedWaitingModel.getStationName() + "】";
        }
        todo.setName(name);
        PrimeFaces.current().executeScript("PF('addStationInfoDialog').hide();getTableScrollHeight()");
    }

    /**
     * 待办评价计划treeTable展示模型
     *
     * @author pengz
     */
    public class ToDoAssessmentModel {
        /**
         * 评价计划id或评价站id
         */
        String psId;
        String name;
        String stationName;
        String responsible;
        String creator;
        Date startTime;
        Date endTime;
        Date actualStratTime;//实际开始
        Date actualEndTime;//实际结束
        int status;
        String type;//InspectionPlan或InspectionStation
        String expert;
        String inspectionType;

        public ToDoAssessmentModel(String psId, String name, String responsible, String creator, Date startTime, Date endTime, Date actualStratTime, Date actualEndTime, int status, String type, String stationName, String expert) {
            this.psId = psId;
            this.name = name;
            this.responsible = responsible;
            this.creator = creator;
            this.startTime = startTime;
            this.endTime = endTime;
            this.actualStratTime = actualStratTime;
            this.actualEndTime = actualEndTime;
            this.status = status;
            this.type = type;
            this.stationName = stationName;
            this.expert = expert;
        }

        public String getPsId() {
            return psId;
        }

        public void setPsId(String psId) {
            this.psId = psId;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getResponsible() {
            return responsible;
        }

        public void setResponsible(String responsible) {
            this.responsible = responsible;
        }

        public String getCreator() {
            return creator;
        }

        public void setCreator(String creator) {
            this.creator = creator;
        }

        public Date getStartTime() {
            return startTime;
        }

        public void setStartTime(Date startTime) {
            this.startTime = startTime;
        }

        public Date getEndTime() {
            return endTime;
        }

        public void setEndTime(Date endTime) {
            this.endTime = endTime;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getStationName() {
            return stationName;
        }

        public void setStationName(String stationName) {
            this.stationName = stationName;
        }

        public Date getActualStratTime() {
            return actualStratTime;
        }

        public void setActualStratTime(Date actualStratTime) {
            this.actualStratTime = actualStratTime;
        }

        public Date getActualEndTime() {
            return actualEndTime;
        }

        public void setActualEndTime(Date actualEndTime) {
            this.actualEndTime = actualEndTime;
        }

        public String getExpert() {
            return expert;
        }

        public void setExpert(String expert) {
            this.expert = expert;
        }

        public String getInspectionType() {
            return inspectionType;
        }

        public void setInspectionType(String inspectionType) {
            this.inspectionType = inspectionType;
        }


    }

    /**
     * 导出当前评价站的评价详情
     */
    public void exportStationExcel(ToDoAssessmentModel todo) {
        String fileDir = commonDocumentProperties.getExportTempPath();
        fileDir = fileDir.endsWith(File.separator) ? fileDir : fileDir + File.separator;
        String fileName = todo.getStationName() + ".xlsx";
        String excelFilePath = fileDir + fileName;
        List<ExportInspectionItemDTO> datas = getExportStationItems(todo.getPsId());
        // 增加一个填写提示
        ExportInspectionItemDTO warnDto = new ExportInspectionItemDTO();
        warnDto.setRiskLevel("如果该项不需要扣分，风险等级请填写‘建议级’");
        warnDto.setEquipmentBay("如果有多个问题间隔，用'[]'分隔，例如：[问题间隔1][问题间隔2]；或者复制一行后填报");
        warnDto.setQuestionAmount("按问题间隔先后顺序依次匹配，用','分隔，例如：2,3；匹配不上的默认问题数量为1");
        warnDto.setProblemDescription("按问题间隔先后顺序依次匹配，用'[]'分隔，例如：[问题间隔1的隐患描述][问题间隔2的隐患描述]");
        warnDto.setRecommendation("按问题间隔先后顺序依次匹配，用'[]'分隔，例如：[问题间隔1的整改建议][问题间隔2的整改建议]");
        warnDto.setImageUrl("按问题间隔先后顺序依次匹配，同一问题间隔的图片用'[]'分隔，例如：[问题间隔1的图片1,图片2][问题间隔2的图片a,图片b]");
        datas.add(0, warnDto);
        // 写入excel
        EasyExcel.write(excelFilePath, ExportInspectionItemDTO.class).sheet(todo.getStationName()).doWrite(datas);
        // 需要导出的图片
        List<RecordImage> exportImages = new ArrayList<RecordImage>();
        for (ExportInspectionItemDTO dto : datas) {
            if (null != dto.getImages()) {
                exportImages.addAll(dto.getImages());
            }
        }
        List<File> fileList = new ArrayList<File>();//需要下载的文件
        File excelFile = new File(excelFilePath);
        fileList.add(excelFile);
        String path = commonDocumentProperties.getImagePath();
        for (RecordImage image : exportImages) {
            File file = new File(path + image.getPath());
            fileList.add(file);
        }
        if (fileList != null && fileList.size() > 0) {
            String zipName = todo.getPsId() + ".zip";
            ZipUtil.zipFile(fileDir + zipName, fileList);
            final File zipFile = new File(fileDir + zipName);
            try {
                InputStream stream = new FileInputStream(zipFile);
                exportFile = new DefaultStreamedContent(stream, "application/zip", URLEncoder.encode(zipName, "UTF-8"));
                addSuccessMessage("导出成功！");
                new Thread() {// 5s后删除文件
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(5000);
                            if (zipFile.exists() && zipFile.isFile()) {// 删除zip
                                zipFile.delete();
                            }
                            if (excelFile.exists() && excelFile.isFile()) {// 删除excel
                                excelFile.delete();
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            } catch (FileNotFoundException | UnsupportedEncodingException e) {
                addErrorMessage("导出失败！");
                e.printStackTrace();
            }
        } else {
            addErrorMessage("导出失败！");
        }
    }

    private List<ExportInspectionItemDTO> getExportStationItems(String stationId) {
        List<ExportInspectionItemDTO> list = new ArrayList<>();
        InspectionStation inspectionStation = deductService.getInspectionStationById(stationId);
        List<InspectionItem> allItems = deductService.getInspectionItems(stationId);
        for (InspectionItem item : allItems) {
            if (item.getItemType() == ItemTypeEnum.INSPECTIONCRITERION) {
                list.add(ExportInspectionItemDTO.convert(imageService, expertService, inspectionStation, item, 0));
            }
        }
//		list.sort(Comparator.comparing(ExportInspectionItemDTO::getInspectionCriterionNo));
        sort(list);
        int no = 1;
        for (ExportInspectionItemDTO d : list) {
            d.setNo(no);
            no++;
        }
        return list;
    }

    /**
     * 根据nodeNo进行排序，以便后续合并相同单元格
     *
     * @param list
     */
    private void sort(List<ExportInspectionItemDTO> list) {
        Collections.sort(list, new Comparator<ExportInspectionItemDTO>() {

            @Override
            public int compare(ExportInspectionItemDTO o1, ExportInspectionItemDTO o2) {
                String[] arr1 = o1.getInspectionCriterionNo().split("\\.");
                String[] arr2 = o2.getInspectionCriterionNo().split("\\.");
                int maxLength = arr1.length > arr2.length ? arr1.length : arr2.length;
                for (int i = 0; i < maxLength; i++) {
                    int i1 = 0;
                    int i2 = 0;
                    if (i < arr1.length) {
                        i1 = Integer.parseInt(arr1[i]);
                    }
                    if (i < arr2.length) {
                        i2 = Integer.parseInt(arr2[i]);
                    }
                    if (i1 > i2) {
                        return 1;
                    } else if (i1 < i2) {
                        return -1;
                    } else {
                        if (i == maxLength - 1) {
                            return 0;
                        } else {
                            continue;
                        }
                    }
                }
                return 0;
            }
        });
    }

    /**
     * 下载InspectionStation模板
     */
//	public void downLoadTemplate() {
//		InputStream stream = null;
//		try {
//			stream = new FileInputStream(new File(pros.getTEMPLETE_PATH()+"InspectionStationTemplate.xlsm"));
//			exportFile = new DefaultStreamedContent(stream, "xlsm", "InspectionStationTemplate.xlsm");
//		} catch (FileNotFoundException e) {
//			addErrorMessage("下载文件失败，请联系技术人员！");
//			e.printStackTrace();
//		}
//	}

    /**
     * 选择上传文件
     */
    public void chooseExcelFile(ToDoAssessmentModel todo) {
        todoModel = todo;
        isDeleteBeforeImport = false;
        InspectionStationWithWaitingDTO model = stationWaitingDtoMap.get(todo.getPsId());
        selectedWaitingModel = model;
        // 判断是否有已评价项目
        if ("InspectionStation".equals(todoModel.getType())) {
            String stationId = todoModel.getPsId();
            InspectionStation is = deductService.getInspectionStationById(stationId);
            // 变电站状态为进行中和已完成时，默认已经评价了部分标准
            if (0 != is.getStatus()) {
                hasFinishedItem = true;
            } else {
                List<InspectionItem> inspectionAll = deductService.getInspectionItems(stationId);
                for (InspectionItem item : inspectionAll) {
                    if (item.getItemType().equals(ItemTypeEnum.INSPECTIONCRITERION)) {
                        if (item.getStatus() == 1 && item.getDeductionCriteria() != 0) {
                            hasFinishedItem = true;
                        }
                    }
                }
            }
        }
        PrimeFaces.current().executeScript("chooseDialog(" + hasFinishedItem + ")");
    }

    public void preUpload() {
        isDeleteBeforeImport = true;
    }

    /**
     * 导入检查站评价信息
     *
     * @param event
     */
    public void handleFileUpload(FileUploadEvent event) {
        String inspectionStationId = todoModel.getPsId();
        if (isDeleteBeforeImport) {
            InspectionStation is = deductService.getInspectionStationById(inspectionStationId);
            SubStationTypeEnum stationType = is.getStationType();
            // 首先清空原有的
            clearInspectionItems();
            selectedWaitingModel.setStationType(stationType.name());
            // 再重新生成
            generateInspectionItems();
        }
        long l1 = System.currentTimeMillis();
        UploadedFile uploadZipFile = event.getFile();
        // zip文件以及解压后的文件暂存到该路径下，
        String tempDir = commonDocumentProperties.getExportTempPath();
        tempDir = tempDir.endsWith(File.separator) ? tempDir : tempDir + File.separator;
        // zip文件暂存路径
        String zipFilePath = tempDir + uploadZipFile.getFileName();
        try {
            OutputStream fos = new FileOutputStream(zipFilePath);
            fos.write(uploadZipFile.getContents());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            addErrorMessage("文件上传失败");
        }
        // 解压文件
        List<File> unzipFiles = ZipUtil.upzipFile(zipFilePath, tempDir);
        // 读取解压文件中的excel信息
        String suffix = "";
        Map<String, String> imageNameAndItemIdMap = new HashMap<String, String>();
        // 记录错误行信息
        StringBuilder errorInfos = new StringBuilder();
        for (File file : unzipFiles) {
            suffix = file.getName().substring(file.getName().lastIndexOf('.'));
            if (suffix.equals(".xlsx") || suffix.equals(".xls")) {
                try {
                    FileInputStream fis = new FileInputStream(file);
                    EasyExcel.read(fis, ExportInspectionItemDTO.class, new InspectionItemExcelDataListener(deductService, inspectionStationId, imageNameAndItemIdMap, expertMap, errorInfos)).sheet().doRead();
                    fis.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    addErrorMessage("文件读取失败");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 上传图片
        uploadImages(unzipFiles, inspectionStationId, imageNameAndItemIdMap);
        // 刷新页面
        refresh(inspectionStationId);
        addSuccessMessage("上传成功");
        // 删除zip
        File zipfile = new File(zipFilePath);
        if (zipfile.exists() && zipfile.isFile()) {
            zipfile.delete();
        }
        deleteFiles(unzipFiles);

        long l2 = System.currentTimeMillis();

        long ll = l2 - l1;
        log.info("耗时：" + ll);

        if (errorInfos != null && errorInfos.length() > 0) {
            errorInfos.append("请核对后重新进行上传");
            alertErrorMessage(errorInfos.toString());
        }
    }

    private void refresh(String stationId) {
        InspectionStation station = deductService.getInspectionStationById(stationId);
        InspectionPlan plan = station.getInspectPlan();
        InspectionStationWithWaitingDTO stationDto = InspectionStationWithWaitingDTO.convertFormInspectionStation(station, plan);
        List<InspectionStationWithWaitingDTO> stationDtos = map.get(plan);
        for (InspectionStationWithWaitingDTO dto : stationDtos) {
            if (dto.getId().equals(stationId)) {
                stationDtos.remove(dto);
                break;
            }
        }
        stationDtos.add(stationDto);
        initPlanTreeTable(allWaitingTasks);

    }

    /**
     * 删除文件
     *
     * @param unzipFiles
     */
    private void deleteFiles(List<File> unzipFiles) {
        File pFile = null;
        for (File file : unzipFiles) {
            if (file.exists() && file.isFile()) {
                pFile = file.getParentFile();
                file.delete();
                File[] children = pFile.listFiles();
                if (0 == children.length) {
                    pFile.delete();
                }
            }
        }
    }

    private void uploadImages(List<File> uploadFiles, String stationId, Map<String, String> imageNameAndItemIdMap) {
        // 所有的图片
        List<RecordImage> allImages = findAllRecordImagesByInspectionStationId(stationId);
        Map<String, List<RecordImage>> imagePathMap = allImages.stream().collect(Collectors.groupingBy(RecordImage::getPath));
        Map<String, List<RecordImage>> imageNameMap = allImages.stream().collect(Collectors.groupingBy(RecordImage::getName));
        String fileSuffix = null;
        String oid = null;
        String imageName = null;
        for (File file : uploadFiles) {
            fileSuffix = file.getName().substring(file.getName().lastIndexOf('.'));
            if (!fileSuffix.equals(".xlsx") && !fileSuffix.equals(".xls")) {
                imageName = file.getName();
                oid = imageNameAndItemIdMap.get(imageName);
                if (null == oid) {
                    continue;
                }
                byte[] content = readFile(file);
                String imageContents = new String(Base64.encodeBytes(content));
                List<RecordImage> lt = imageNameMap.get(imageName);
                if (null == lt || 0 == lt.size()) {
                    lt = imagePathMap.get(imageName);
                }
                RecordImage image = new RecordImage();
                if (lt != null && lt.size() > 0) {
                    image = lt.get(0);
                }
                try {
                    imageService.upload(image.getId(), oid, imageName, image.getOrderNo(), image.getCreator(), image.getRemark(), imageContents, image.getThumbnail(), AttachmentType.PICTURE, false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private byte[] readFile(File file) {
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data);
//			in.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return data;
    }

    private List<RecordImage> findAllRecordImagesByInspectionStationId(String inspectionStationId) {
        List<RecordImage> allImages = new ArrayList<RecordImage>();
        // 获取Item
        List<InspectionItem> criterionItems = itemService.findBySubIdAndItemType(inspectionStationId, ItemTypeEnum.INSPECTIONCRITERION);
        for (InspectionItem inspectionItem : criterionItems) {
            try {
                allImages.addAll(imageService.findRecordImageByOid(inspectionItem.getId()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                List<InspectionQuestionEquipment> qes = qeService.findByInspectionItem(inspectionItem.getId());
                for (InspectionQuestionEquipment qe : qes) {
                    allImages.addAll(imageService.findRecordImageByOid(qe.getId()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return allImages;
    }

    /**
     * 获取所有的专家map
     *
     * @return
     */
    private Map<String, InspectionExpert> getAllExpert() {
        List<InspectionExpert> experts = expertService.findAll();
        Map<String, InspectionExpert> expertNameMap = new HashMap<String, InspectionExpert>();
        for (InspectionExpert e : experts) {
            expertNameMap.put(e.getName(), e);
        }
        return expertNameMap;
    }

    public void preGenRectificationPlan(ToDoAssessmentModel model) {
        todoModel = model;
        createTrackDemo = new RectificationPlan();
    }

    /**
     * 重新生成检查站的整改计划
     */
    public void regenRectificationPlan() {
        createTrackDemo.setPersonInChargeCode(selectedPerson.getCode());
        createTrackDemo.setPersonInChargeName(selectedPerson.getName());
        createTrackDemo.setPersonInChargePhone(selectedPerson.getTelephone());

        String inspectionStationId = todoModel.getPsId();
        // 先将该站下的整改计划删除掉
        rectificationPlanService.deleteByInspectionStationId(inspectionStationId);
        // 重新生成
        List<RectificationPlan> rplans = new ArrayList<RectificationPlan>();
        InspectionStation inspectionStation = deductService.getInspectionStationById(inspectionStationId);
        InspectionPlan plan = inspectionStation.getInspectPlan();
        List<InspectionItem> items = deductService.getInspectionItems(inspectionStationId);
        for (InspectionItem item : items) {
            List<InspectionQuestionEquipment> equipments = item.getQuestionEquipments();
            for (InspectionQuestionEquipment qe : equipments) {
                rplans.add(new RectificationPlan(plan, inspectionStation, item, qe, createTrackDemo.getPlanStartDate(), createTrackDemo.getPlanFinishDate(), createTrackDemo.getPersonInChargeCode(), createTrackDemo.getPersonInChargeName(), createTrackDemo.getPersonInChargePhone()));
            }
        }
        try {
            rectificationPlanService.createRectificationPlans(rplans);
        } catch (Exception e) {
            e.printStackTrace();
            addErrorMessage("批量生成整改计划出错");
            return;
        }
        addSuccessMessage("整改计划生成成功");
        for (RectificationPlan rp : rplans) {
            afterCreate(rp, -30);
        }
    }

    /**
     * 整改计划生成后，如果在整改计划开始时间的前【dayDelay天】还未进行整改，增加提醒功能
     *
     * @param rectificationPlan
     * @param dayDelay
     */
    private void afterCreate(RectificationPlan rectificationPlan, int dayDelay) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(rectificationPlan.getCreateTime().getTime());
        c.add(Calendar.DATE, dayDelay);
        Date newDate = new Date(c.getTimeInMillis());
        addReminderTimer(rectificationPlan.getId(), newDate);
    }

    private void addReminderTimer(String rectificationPlanId, Date date) {
        if (null == date) {
            return;
        }
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                RectificationPlan rectificationPlan = rectificationPlanService.findById(rectificationPlanId);
                // 该条整改计划还存在，并且还未整改
                if (null != rectificationPlan && 1 != rectificationPlan.getStatus()) {
                    List<String> phoneList = new ArrayList<String>();
                    phoneList.add(rectificationPlan.getPersonInChargePhone());
                    String mesgContent = rectificationPlan.getStationName() + "--" + rectificationPlan.getEquipmentName() + "待整改，请登录系统填写整改方案！";
                    try {
                        mosMessM.sendMsgByMass(phoneList, "整改计划提醒通知", mesgContent);
                    } catch (Exception e) {
                        e.printStackTrace();
                        addErrorMessage("短信推送异常");
                    }
                }
            }
        }, date);
    }

    /**
     * 整改负责人选定事件
     *
     * @param event
     */
    public void onChargePersonSelected(SelectEvent event) {
        String pId = (String) event.getObject();
        selectedPerson = pm.findPersonnelById(pId);
        createTrackDemo.setPersonInChargePhone(selectedPerson.getTelephone());
    }

    /**
     * 获取整改负责人可选列表
     * 互查计划：被检单位下的人员
     * 自查计划：检查单位下的人员
     *
     * @param planId
     * @return
     */
    private List<PersonnelEntityBean> getPersonInCharge() {
        InspectionStation is = deductService.getInspectionStationById(todoModel.getPsId());
        String dept = is.getAcceptUnit();
        // 根据dept获取人员
        List<DepartmentEntityBean> depts = dm.findDepartmentsByName(dept);
        List<PersonnelEntityBean> persons = new ArrayList<PersonnelEntityBean>();
        for (DepartmentEntityBean d : depts) {
            persons.addAll(dm.findDeptPersonnels(d.getId()));
        }
        return persons;
    }

    /**
     * 整改负责人选择
     */
    public List<PersonnelEntityBean> completePersonInCharge(String query) {
        List<PersonnelEntityBean> allPersons = getPersonInCharge();
        List<PersonnelEntityBean> results = new ArrayList<PersonnelEntityBean>();
        for (PersonnelEntityBean p : allPersons) {
            String nameHead = PingYinUtil.getPingYinHeader(p.getName());
            if (nameHead.toLowerCase().contains(query)) {
                results.add(p);
            }
        }
        return results;
    }


    public TreeNode getRoot() {
        return root;
    }

    public void setRoot(TreeNode root) {
        this.root = root;
    }

    public String getStatusColor() {
        return statusColor;
    }

    public void setStatusColor(String statusColor) {
        this.statusColor = statusColor;
    }

    public List<InspectionPlan> getAllWaitingTasks() {
        return allWaitingTasks;
    }

    public void setAllWaitingTasks(List<InspectionPlan> allWaitingTasks) {
        this.allWaitingTasks = allWaitingTasks;
    }

    public InspectionStationWithWaitingDTO getSelectedWaitingModel() {
        return selectedWaitingModel;
    }

    public void setSelectedWaitingModel(InspectionStationWithWaitingDTO selectedWaitingModel) {
        this.selectedWaitingModel = selectedWaitingModel;
    }

    public boolean isIsExpert() {
        return isExpert;
    }

    public void setExpert(boolean isExpert) {
        this.isExpert = isExpert;
    }

    public boolean isCurrentExpertlogin() {
        return currentExpertlogin;
    }

    public void setCurrentExpertlogin(boolean currentExpertlogin) {
        this.currentExpertlogin = currentExpertlogin;
    }

    public StreamedContent getExportFile() {
        return exportFile;
    }

    public void setExportFile(StreamedContent exportFile) {
        this.exportFile = exportFile;
    }

    public boolean isHasFinishedItem() {
        return hasFinishedItem;
    }

    public void setHasFinishedItem(boolean hasFinishedItem) {
        this.hasFinishedItem = hasFinishedItem;
    }

    public RectificationPlan getCreateTrackDemo() {
        return createTrackDemo;
    }

    public void setCreateTrackDemo(RectificationPlan createTrackDemo) {
        this.createTrackDemo = createTrackDemo;
    }


}
